import 'dart:convert';
import 'package:injectable/injectable.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/storage_service.dart';

/// 认证
/// 处理用户登录、注册、注销等操作
@lazySingleton
class AuthFocus {
  final StorageService _storageService;
  static const String _usersKey = 'users';
  static const String _currentUserKey = 'current_user';
  static const String _isInitializedKey = 'users_initialized';

  AuthFocus(this._storageService);

  /// 初始化默认用户数据
  Future<void> initializeDefaultUsers() async {
    final isInitialized = await _storageService.retrieveBool(_isInitializedKey);
    if (isInitialized == true) {
      return; // 已经初始化过了
    }

    // 创建默认用户
    final defaultUsers = [
      UserFrame(
        id: '1',
        account: 'admin',
        username: 'Grace',
        password: '123456', // 实际项目中应该加密
        avatar: 'assets/images/avatar1.png',
        signature: 'Capture the moment',
      ),
      UserFrame(
        id: '2',
        account: 'user1',
        username: 'Sophia',
        password: 'user123',
        avatar: 'assets/images/avatar2.png',
        signature: 'Light & Shadow',
      ),
      UserFrame(
        id: '3',
        account: 'user2',
        username: 'Mason',
        password: 'user123',
        avatar: 'assets/images/avatar3.png',
        signature: 'Through my lens',
      ),
      UserFrame(
        id: '4',
        account: 'user3',
        username: 'Logan',
        password: 'user123',
        avatar: 'assets/images/avatar4.png',
        signature: 'Framing life',
      ),
      UserFrame(
        id: '5',
        account: 'user4',
        username: 'Liam',
        password: 'user123',
        avatar: 'assets/images/avatar5.png',
        signature: 'Shutter stories',
      ),
      UserFrame(
        id: '6',
        account: 'user5',
        username: 'Noah',
        password: 'user123',
        avatar: 'assets/images/avatar6.png',
        signature: 'Focused vision',
      ),
      UserFrame(
        id: '7',
        account: 'user6',
        username: 'Isabella',
        password: 'user123',
        avatar: 'assets/images/avatar7.png',
        signature: 'Photo journey',
      ),
      UserFrame(
        id: '8',
        account: 'user7',
        username: 'Harper',
        password: 'user123',
        avatar: 'assets/images/avatar8.png',
        signature: 'Lens artist',
      ),
      UserFrame(
        id: '9',
        account: 'user8',
        username: 'Julian',
        password: 'user123',
        avatar: 'assets/images/avatar9.png',
        signature: 'Visual tales',
      ),
      UserFrame(
        id: '10',
        account: 'user9',
        username: 'Cora',
        password: 'user123',
        avatar: 'assets/images/avatar10.png',
        signature: 'Image maker',
      ),
    ];

    // 保存默认用户
    await saveUsers(defaultUsers);
    await _storageService.persistBool(_isInitializedKey, true);
  }

  /// 保存用户列表
  Future<void> saveUsers(List<UserFrame> users) async {
    final usersJson = users.map((user) => user.toJson()).toList();
    final usersString = jsonEncode(usersJson);
    await _storageService.persistString(_usersKey, usersString);
  }

  /// 获取所有用户
  Future<List<UserFrame>> getUsers() async {
    final usersString = await _storageService.retrieveString(_usersKey);
    if (usersString == null) {
      return [];
    }

    try {
      final List<dynamic> usersJson = jsonDecode(usersString);
      return usersJson
          .map((json) => UserFrame.fromJson(json as Map<String, dynamic>))
          .toList();
    } catch (e) {
      return [];
    }
  }

  /// 根据账号查找用户
  Future<UserFrame> findUserByAccount(String account) async {
    final users = await getUsers();
    try {
      return users.firstWhere((user) => user.account == account);
    } catch (e) {
      throw Exception('User not found');
    }
  }

  /// 检查账号是否已存在
  Future<bool> isAccountExists(String account) async {
    try {
      await findUserByAccount(account);
      return true;
    } catch (e) {
      if (e.toString().contains('User not found')) {
        return false;
      }
      return false;
    }
  }

  /// 注册新用户
  Future<UserFrame> register({
    required String account,
    required String username,
    required String password,
    String? avatar,
    String? signature,
  }) async {
    // 检查账号是否已存在
    if (await isAccountExists(account)) {
      throw Exception('Account already exists');
    }

    // 如果没有提供签名，使用默认签名
    final defaultSignatures = [
      'Capture the moment',
      'Light & Shadow',
      'Through my lens',
      'Framing life',
      'Shutter stories',
      'Focused vision',
      'Photo journey',
      'Lens artist',
      'Visual tales',
      'Image maker',
    ];
    final finalSignature =
        signature ??
        defaultSignatures[DateTime.now().millisecondsSinceEpoch %
            defaultSignatures.length];

    // 创建新用户
    final users = await getUsers();
    final newUser = UserFrame(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      account: account,
      username: username,
      password: password,
      avatar: avatar,
      signature: finalSignature,
    );

    users.add(newUser);
    await saveUsers(users);

    return newUser;
  }

  /// 用户登录
  Future<UserFrame> login({
    required String account,
    required String password,
  }) async {
    final user = await findUserByAccount(account);
    if (user.password != password) {
      throw Exception('Invalid password');
    }

    // 保存当前登录用户
    await _storageService.persistString(
      _currentUserKey,
      jsonEncode(user.toJson()),
    );

    return user;
  }

  /// 获取当前登录用户
  Future<UserFrame?> getCurrentUser() async {
    final userString = await _storageService.retrieveString(_currentUserKey);
    if (userString == null) {
      return null;
    }

    try {
      final userJson = jsonDecode(userString) as Map<String, dynamic>;
      return UserFrame.fromJson(userJson);
    } catch (e) {
      return null;
    }
  }

  /// 检查是否已登录
  Future<bool> isLoggedIn() async {
    final currentUser = await getCurrentUser();
    return currentUser != null;
  }

  /// 注销登录
  Future<void> logout() async {
    await _storageService.removeKey(_currentUserKey);
  }

  /// 更新用户信息
  Future<UserFrame> updateUserInfo({
    required String account,
    String? username,
    String? avatar,
    String? signature,
  }) async {
    // 查找用户
    final user = await findUserByAccount(account);

    // 创建更新后的用户
    final updatedUser = UserFrame(
      id: user.id,
      account: user.account,
      username: username ?? user.username,
      password: user.password,
      avatar: avatar ?? user.avatar,
      signature: signature ?? user.signature,
    );

    // 更新用户列表
    final users = await getUsers();
    final index = users.indexWhere((u) => u.account == account);
    if (index != -1) {
      users[index] = updatedUser;
      await saveUsers(users);
    }

    // 如果更新的是当前登录用户，更新缓存
    final currentUser = await getCurrentUser();
    if (currentUser != null && currentUser.account == account) {
      await _storageService.persistString(
        _currentUserKey,
        jsonEncode(updatedUser.toJson()),
      );
    }

    return updatedUser;
  }
}
